import {
  GraphQLList,
  GraphQLObjectType,
  GraphQLSchema,
  GraphQLString,
  GraphQLInt,
  GraphQLFloat,
  GraphQLEnumType,
  GraphQLNonNull
} from 'graphql'
import mongo from '../mongo'
import StockBasicsType from './types/StockBasicsType'
import StockDailySummeryType from './types/StockDailySummeryType'

export const stockList = {
  type: new GraphQLList(StockBasicsType),
  description: '获取股票列表',
  args: {
    industry: {
      type: GraphQLString,
      description: '行业分类'
    },
    area: {
      type: GraphQLString,
      description: '地区' // 暂时支持省级查询
    },
    skip: {
      type: GraphQLInt,
      description: '跳过条目数'
    },
    limit: {
      type: GraphQLInt,
      description: '限制条目数'
    }
  },
  resolve: async function (_, args) {
    let db = await mongo
    let collection = db.collection('stock_list');

    return new Promise(function (resolve, reject) {
      let query = {}

      if (args.industry) {
        query.industry = {
          '$eq': args.industry
        }
      }

      if (args.area) {
        query.area = {
          '$eq': args.area
        }
      }

      collection.find(query, {fields: {}}).skip(args.skip || 0).limit(args.limit || Number.MAX_SAFE_INTEGER).toArray(function(err, doc) {
        resolve(doc)
      })
    })
  }
}

export const stockBasics = {
  type: StockBasicsType,
  description: '获取单支股票信息',
  args: {
    code: {
      type: GraphQLString,
      description: '股票代码'
    }
  },
  resolve: async function (_, args) {
    let db = await getStockDb()

    let collection = db.collection('stock_basics')

    return new Promise(function (resolve, reject) {
      collection.findOne({code: { '$eq': args.code }}, {fields: {}}, function(err, doc) {
        resolve(doc)
      })
    })
  }
}

export const updateStock = {
  type: GraphQLFloat,
  resolve: function (_, args) {
    return ''
  }
}

export const stockDailySummery = {
  type: new GraphQLList(StockDailySummeryType),
  description: '获取日线信息',
  args: {
    code: {
      type: GraphQLString,
      description: '股票代码'
    },
    start: {
      type: GraphQLInt,
      description: '开始日期'
    },
    end: {
      type: GraphQLInt,
      description: '结束日期'
    }
  },
  resolve: async function (_, args) {
    let db = await mongo

    let collection = db.collection('stock_' + args.code)

    if (args.start > args.end) {
      throw Object('开始日期不能大于结束日期')
    }

    return new Promise(function (resolve, reject) {
      collection.find({_id: { '$gte': args.start, '$lte': args.end }}, {fields: {}}).toArray(function(err, doc) {
        doc = doc.map(item => {
          item.date = item._id // ('' + item._id).match(/([0-9]{4})([0-9]{2})([0-9]{2})/).slice(1).join('-')
          item._id = null
          delete item._id
          return item
        })

        resolve(doc)
      })
    })
  }
}
